<template>
  <div class="params">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
        <el-alert
          title="注意:只允许为第三级分类设置参数!"
          type="warning"
          show-icon>
        </el-alert>
        <el-row>
          <el-col>
            <span>选择商品分类:</span>
            <el-cascader
              v-model="selected_cascade"
              :options="cate_list"
              :props="cate_props"
              @change="handleCascadeChange">
            </el-cascader>
          </el-col>
        </el-row>
        <!-- tab栏 -->
         <el-tabs v-model="tab_selected" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button :disabled="addParamsFlag" type="primary" size="mini" @click="addDialogVisible=true">添加参数</el-button>
            <el-table stripe border :data="manyParams" style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="closeTag(scope.row,index)" type="primary" closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.tagBtnVisible"
                    v-model="tagInputValue"
                    ref="tagInputRef"
                    size="small"
                    @keyup.enter.native="handleTagInput(scope.row)"
                    @blur="handleTagInput(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" @click="showEditParams(scope.row)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" @click="delParams(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button :disabled="addParamsFlag" type="primary" size="mini" @click="addDialogVisible=true">添加属性</el-button>
            <el-table stripe border :data="onlyParams" style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="closeTag(scope.row,index)" type="primary" closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.tagBtnVisible"
                    v-model="tagInputValue"
                    ref="tagInputRef"
                    size="small"
                    @keyup.enter.native="handleTagInput(scope.row)"
                    @blur="handleTagInput(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" @click="showEditParams(scope.row)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" @click="delParams(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加参数/添加属性的弹窗 -->
    <el-dialog
    @close='addDialogClose'
      :title="'添加'+paramsOrAttr"
      :visible.sync="addDialogVisible"
      width="50%"
      >
      <el-form ref="addFormRef" :rules="addRules" :model="addForm" label-width="100px" prop="addProps">
        <el-form-item :label="paramsOrAttr" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数/添加属性的弹窗 -->
    <el-dialog
    @close='editDialogClose'
      :title="'编辑'+paramsOrAttr"
      :visible.sync="editDialogVisible"
      width="50%"
      >
      <el-form ref="editFormRef" :rules="editRules" :model="editForm" label-width="100px" prop="editProps">
        <el-form-item :label="paramsOrAttr" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default{
  data(){
    return {
      cate_list:[],//商品分类级联列表数据
      selected_cascade:[],//选中的级联的值,即商品ID数组
      cate_props:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        expandTrigger: 'hover' //级联选择器配置项
      },
      tab_selected:'many',//当前tab栏的位置
      addParamsFlag:true,
      manyParams:[],//动态参数列表
      onlyParams:[],//静态属性列表
      addDialogVisible:false,//添加参数/属性的弹窗
      addForm:{
        attr_name:''
      },//添加参数/属性的表单
      addRules:{
        attr_name:[
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible:false,
      editForm:{
        cat_id:'',
        attr_id:'',
        attr_name:'',
        attr_sel:'',
      },
      editRules:{
        attr_name:[
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // tagBtnVisible:false,
      tagInputValue:''
    }
  },
  created(){
    this.initCateList()
  },
  computed:{
    paramsOrAttr(){
      if(this.tab_selected=='many'){
        return '动态参数'
      }else{
        return '静态属性'
      }
    }
  },
  methods:{
    async initCateList(){
      const res= await this.$http.get('categories')
      // console.log(res);
      if(res.data.meta.status!==200) return this.$message.error('数据获取失败')
      this.cate_list=res.data.data
    },
    //级联选择器的值改变事件
    handleCascadeChange(){
      if(this.selected_cascade.length!==3){
        this.selected_cascade=[]
        this.manyParams=[]
        this.onlyParams=[]
        this.addParamsFlag=true
        return 
      }
      this.getParamsList()
      this.addParamsFlag=false
    },
    handleTabClick(){
      this.getParamsList()
    },
    //获取参数列表
    async getParamsList(){
        const res = await this.$http.get(`categories/${this.selected_cascade[this.selected_cascade.length-1]}/attributes`,{params:{sel:this.tab_selected}})
        // console.log(res);
        res.data.data.forEach(item=>{
            item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
            item.tagBtnVisible=false
          })
        if(this.tab_selected=='many'){
          this.manyParams=res.data.data
          console.log(this.manyParams);
        }else{
          this.onlyParams=res.data.data
          console.log(this.onlyParams);
        }
    },
    addDialogClose(){
      this.$refs.addFormRef.resetFields()
    },
    confirmAdd(){
      this.$refs.addFormRef.validate(async valid=>{
        if(valid){
          const res=await this.$http.post(`categories/${this.selected_cascade[this.selected_cascade.length-1]}/attributes`,{
            attr_name:this.addForm.attr_name,
            attr_sel:this.tab_selected
          })
          // console.log(res);
          if(res.data.meta.status!==201) return this.$message.error('创建失败')
          this.$message.success('创建成功')
          this.getParamsList()
          this.addDialogVisible=false
        }
      })
    },
    async showEditParams(row){
      const res=await this.$http.get(`categories/${row.cat_id}/attributes/${row.attr_id}`)
      // console.log(res);
      if(res.data.meta.status!==200) return this.$message.error('获取数据失败')
      this.editForm.cat_id=res.data.data.cat_id
      this.editForm.attr_id=res.data.data.attr_id
      this.editForm.attr_name=res.data.data.attr_name
      this.editForm.attr_sel=res.data.data.attr_sel
      // console.log(this.editForm);
      this.editDialogVisible=true
    },
    editDialogClose(){
      // this.editForm.cat_id
      this.$refs.editFormRef.resetFields()
    },
    confirmEdit(){
      this.$refs.editFormRef.validate(async valid=>{
        if(valid){  
          const res=await this.$http.put(`categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,{
            attr_name:this.editForm.attr_name,
            attr_sel:this.editForm.attr_sel
          })
          // console.log(res);
          if(res.data.meta.status!==200) return this.$message.error('更新失败')
          this.$message.success('更新成功')
          this.getParamsList()
          this.editDialogVisible=false
        }
      })
    },
    async delParams(row){
      const flag=await this.$confirm('此操作将永久删除该参数,是否确定','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).catch(err=>{
        return  err
      })
      if(flag=='confirm'){
        const res=await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
        if(res.data.meta.status!==200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParamsList()
      }
    },
    //enter添加标签
    async handleTagInput(row){
      if(this.tagInputValue.trim()==''){
        this.tagInputValue=''
        row.tagBtnVisible = false;
        return 
      }
      row.attr_vals.push(this.tagInputValue.trim())
      this.updateTag(row)
      // this.tagInputValue=''
    },
    showTagInput(row){
      row.tagBtnVisible = true;
      this.$nextTick(()=> {
        this.$refs.tagInputRef.$refs.input.focus();
      });
    },
    async closeTag(row,index){
      console.log(row,index);
      row.attr_vals.splice(index,1)
      this.updateTag(row)
    },
    //公用的更新标签的方法
    async updateTag(row){
      const res= await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(' ')
      })
      // console.log(res);
      if(res.data.meta.status!==200) this.$message.error('更新失败')
      this.tagInputValue=''
      row.tagBtnVisible = false;
    }
  }
}
</script>

<style lang="less" scoped>
.params{
  .el-card{
    margin-top: 20px;
    .el-alert{
      margin-bottom: 20px;
    }
    .el-row{
      .el-cascader{
        width: 300px;
        margin-left: 20px;
      }
    }
    .el-tabs{
      .el-tab-pane{
        >.el-button{
          margin-bottom: 20px;
        }
        .el-tag{
          margin: 0 15px;
        }
        .input-new-tag{
          width: 180px;
        }
      }
    }
  }
}
</style>